from email.header import decode_header
import email
import imaplib
import smtplib
from email.mime.text import MIMEText
from constant.param_config import openSendMail
import threading
import time

from utils.log_util import saveLog
from utils.time_util import current_time

# SMTP服务器地址和端口号
smtp_server = 'smtp.163.com'
smtp_port = 465

# IMAP服务器地址和端口号
imap_server = 'imap.163.com'
imap_port = "993"

# 发送方邮箱地址和密码
sender_email = '13323392673@163.com'
sender_password = 'ZNBMIOUSVDBARBMC'
# 收件人邮箱地址
recipient_email = '13323392673@163.com'

delete_title = ["当前价格为", "有重要数据公布", "重要数据已公布"]
delay = 300
last = 0


def cleanMail():
    cleanThread = threading.Thread(target=executeClean)
    cleanThread.start()


def sendMail(title="", msg="", timer=True, send=False):
    if openSendMail is False and send is False:
        return

    thread = threading.Thread(target=execution, args=[title, msg, timer])
    thread.start()


def execution(title="", msg="", timer=True):
    """
    timer  是否中断计时
    """

    try:
        global last
        if timer:
            if last != 0 and current_time() - last < delay:
                return
            last = current_time()

        if title == "" and msg == "":
            saveLog("email 发送失败")
            return

        # 邮件主题和正文
        if title == "":
            mail_subject = '交易提醒' + '——' + msg
        else:
            mail_subject = title

        # 创建SMTP对象
        smtpObj = smtplib.SMTP_SSL(smtp_server, smtp_port)

        # 登录SMTP服务器
        smtpObj.login(sender_email, sender_password)

        # 发送邮件
        message = MIMEText(msg, 'plain', 'utf-8')
        message['Subject'] = mail_subject
        message['From'] = sender_email
        message['To'] = recipient_email
        smtpObj.sendmail(sender_email, recipient_email, message.as_string())
        time.sleep(3)
        # 关闭SMTP连接
        smtpObj.quit()
        saveLog("邮件发送成功")
    except Exception as e:
        saveLog("邮件发送异常：" + str(e))


def executeClean():
    try:
        # 添加缺失的命令
        imaplib.Commands['ID'] = ('AUTH')

        conn = imaplib.IMAP4_SSL(port=imap_port, host=imap_server)
        state, info = conn.login(sender_email, sender_password)

        if state == "OK":
            # 上传客户端身份信息
            args = (sender_email, "XXXX", "contact", sender_email, "version",
                    "1.0.0", "vendor", "myclient")
            typ, dat = conn._simple_command('ID',
                                            '("' + '" "'.join(args) + '")')
            result, msgs = conn.select('INBOX', False)

            if result == "OK":
                result, data = conn.search(None, 'ALL')
                email_list = data[0].split()

                sendMail("开始清理冗余邮件")

                for num in email_list:
                    v_type, data = conn.fetch(num, '(RFC822)')
                    if v_type == "OK" and data[0] != None:
                        result = (data[0][1]).decode('utf-8')
                        msg = email.message_from_string(result)

                        date = msg["Date"]
                        subject = decode_header(msg["Subject"])[0][0]

                        if isinstance(subject, bytes):
                            subject = subject.decode()

                        titleList = [
                            item for item in delete_title if item in subject
                        ]

                        if len(titleList) != 0:
                            conn.store(num, '+FLAGS', '\\Deleted')
                sendMail("冗余邮件清理完成")
    except Exception as e:
        saveLog("邮件清理异常：" + str(e))


if __name__ == '__main__':
    saveLog("发送邮件")
    sendMail("ceshi")
